import { ONE_LINK, TIYA_SHARE_SCHEME } from '@/config/constant'

// 第一时间获取客户端信息
export function getAppInfo() {
  const APP_INFO = {
    model: 'localhost',
    version: '1.2.1',
    buildVersion: '111111',
    system: 'localhost',
    deviceId: '123456789',
    platform: 'localhost',
    lang: 'EM',
  }
  return new Promise((resolve) => {
    if (window.lz.isApp) {
      if (window.LizhiJSBridge) {
        window.LizhiJSBridge.call('getAppInfo', {}, (ret) => {
          resolve(ret.version ? ret : APP_INFO)
        })
      } else {
        document.addEventListener('LizhiJSBridgeReady', () => {
          window.LizhiJSBridge.call('getAppInfo', {}, (ret) => {
            resolve(ret.version ? ret : APP_INFO)
          })
        })
      }
    } else {
      resolve(APP_INFO)
    }
  })
}

export const handleGetToken = (manual_token, fresh = false, requestUrl = '') => {
  return new Promise((resolve, reject) => {
    try {
      if (window.lz.isApp) {
        window.lz.Ready(async () => {
          const { token } = await window.lz.getToken({ needRefresh: fresh }).catch((err) => {
            return err
          })
          resolve(token)
          console.info(`requestUrl:${requestUrl}调用getToken，fresh:${fresh},token:${token}`)
        })
      } else {
        resolve(manual_token)
      }
    } catch (err) {
      reject(err)
    }
  })
}

function recuriseStringify(obj) {
  // 暂不考虑循环引用的问题
  const temp = {}
  Object.entries(obj).forEach(([key, value]) => {
    if (Array.isArray(value)) {
      temp[key] = value.map((v) => recuriseStringify(v))
    } else if (value !== null && typeof value === 'object') {
      temp[key] = recuriseStringify(value)
    } else {
      temp[key] = value
    }
  })
  return JSON.stringify(temp)
}

function wakeUpAppWithAction({ action }) {
  // NOTE: 实测安卓最外层stringify就可以，而IOS需要递归的stringify，待解释。
  const actionStr = recuriseStringify(action)
  const wakeUpLink = TIYA_SHARE_SCHEME + encodeURIComponent(actionStr)
  window.location.href = wakeUpLink
}

function redirectOneLinkAfterWakeUpFail({ delay, onelink }) {
  const timer = setTimeout(() => {
    window.location.href = onelink
  }, delay)
  // 页面隐藏，那么代表已经调起了app，就清除下载的定时器
  const visibilitychange = function () {
    const tag = document.hidden || document.webkitHidden
    tag && clearTimeout(timer)
  }

  document.addEventListener('visibilitychange', visibilitychange, false)
  document.addEventListener('webkitvisibilitychange', visibilitychange, false)
  window.addEventListener(
    'pagehide',
    function () {
      clearTimeout(timer)
    },
    false,
  )
}

export function handleRedirectOutOfApp() {
  return new Promise((resolve, reject) => {
    try {
      window.lz.Ready(function () {
        if (!window.lz.isApp) {
          resolve(true)
          redirectOneLinkAfterWakeUpFail({ delay: 2500, onelink: ONE_LINK })
          const action = {
            action: {
              type: 6,
              scheme: 'common/webView',
              extraData: {
                url: window.location.href,
              },
            },
            type: 'jump',
          }
          wakeUpAppWithAction({ action })
        }
        resolve(false)
      })
    } catch (err) {
      reject(err)
    }
  })
}

// TODO: 后面抽一个bridge版的 promise包装器
export const getSessionUserId = () => {
  return new Promise((resolve, reject) => {
    window.lz.Ready(() => {
      window.lz.getSessionUserId({}, ({ id }) => {
        if (id === '0') {
          reject('未登录')
        } else {
          resolve(id)
        }
      })
    })
  })
}

export const appShareLink = async ({ shareUrl, shareOutsideUrl }) => {
  window.lz.Ready(() => {
    window.lz.shareUrl(
      {
        type: 0,
        url: shareUrl,
        outsideUrl: shareOutsideUrl,
        imageUrl: 'http://fepublicty.tiyalive.com/tiya/activities/us-halloween/banner.png',
        title: 'Join the event for a chance to win up to $10,000 Robux',
        content: 'Share your screen to receive rewards!',
        extraData: {},
      },
      // 回调时不时失灵的，垃圾！
      // function (ret) {
      //   console.log('分享链接成功：', ret)
      // },
    )
  })
}
